/*
 * @Description:
 * @Version: 2.0
 * @Author: Xing
 * @Date: 2020-08-13 16:16:08
 * @LastEditors: Xing
 * @LastEditTime: 2020-08-14 17:49:19
 */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Form, Input, Button, Checkbox, message, Space } from 'antd';
import './login.css';

import { loginApi } from '../../request/login';

const layout = {
  labelCol: {
    span: 8,
  },
  wrapperCol: {
    span: 16,
  },
};
const tailLayout = {
  wrapperCol: {
    offset: 8,
    span: 16,
  },
};

const onFinish = (values) => {
  console.log('Success:', values);
};

const onFinishFailed = (errorInfo) => {
  console.log('Failed:', errorInfo);
};

export class login extends Component {
  constructor(props) {
    super(props);
  }
  static propTypes = {};

  state = {
    user_name: '',
    password: '',
  };

  handleLogin() {
    let data = {
      password: this.state.password,
      user_name: this.state.user_name,
    };
    loginApi(data).then(
      (res) => {
        if (res.ret === 0) {
          localStorage.setItem('app_id', res.data.app_id);
          localStorage.setItem('app_id', res.data.app_id);
          localStorage.setItem('token', res.data.token);
          this.props.history.push('/index');
        } else {
          message.error(res.msg || '登录失败');
        }
      },
      (error) => {
        message.error('网络错误');
      }
    );
  }

  //   获取用户名
  handleGetUserName = (event) => {
    if (event && event.target && event.target.value) {
      let value = event.target.value;
      this.setState(() => ({ user_name: value }));
    }
  };

  //   获取密码
  handleGetPassword = (event) => {
    if (event && event.target && event.target.value) {
      let value = event.target.value;
      this.setState(() => ({ password: value }));
    }
  };

  render() {
    return (
      <div className="form-back-box">
        <Form className="form-box" {...layout} name="basic" initialValues={{ remember: true }} onFinish={onFinish} onFinishFailed={onFinishFailed}>
          <Form.Item label="Username" name="username" rules={[{ required: true, message: 'Please input your username!' }]}>
            <Input
              onChange={(e) => {
                this.handleGetUserName(e);
              }}
            />
          </Form.Item>

          <Form.Item label="Password" name="password" rules={[{ required: true, message: 'Please input your password!' }]}>
            <Input.Password
              onChange={(e) => {
                this.handleGetPassword(e);
              }}
            />
          </Form.Item>

          <Form.Item {...tailLayout} name="remember" valuePropName="checked">
            <Checkbox>Remember me</Checkbox>
          </Form.Item>

          <Form.Item {...tailLayout}>
            <Button type="primary" htmlType="submit" onClick={this.handleLogin.bind(this)}>
              Submit
            </Button>
          </Form.Item>
        </Form>
      </div>
    );
  }
}

export default login;
